<script setup lang="ts">
import Spreadsheet from "x-data-spreadsheet";
import * as XLSX from 'xlsx/xlsx.mjs'
import { nextTick, ref } from "vue";
import demo from './demo.js'
import defaultoptions from './defaultoptions.js'
import  { setLocale } from './locales.js'
import {  xtos } from './xlsxspread.js'
import 'vue-json-pretty/lib/styles.css'
import VueJsonPretty from 'vue-json-pretty'
import { ElMessage } from "element-plus";

const spreadsheetElRef = ref(); // ele元素
const spreadsheetRef = ref(); // 实例对象
const initSpreadsheet = () => {
  visible.value = true
  nextTick(()=> {
    // 国际化
    // Spreadsheet.locale('zh-cn', zhCN);
    localeHandle();
    // 初始化
    spreadsheetRef.value = new Spreadsheet(spreadsheetElRef.value, 
      mergeOptions({
        // 覆盖默认配置
        showToolbar: true,
        showGrid: true,
        showContextmenu: true,
        mode: 'read',
        view: {
          height: () => spreadsheetElRef.value.clientHeight || 500,
          width: () => spreadsheetElRef.value.clientWidth || 800,
        }})
      )
  })
}

// 默认配置对象
const mergeOptions = (options: any) => Object.assign({},
      defaultoptions,
      options
  )

// 定义语言包及使用
const localeHandle = () => {
// 设置x-spreadsheet的本地化
  // 注册中文语言包
  setLocale('zh-cn', 'zh-CN')
}

const loaddata = () => {
  let data = JSON.parse(JSON.stringify(demo));
  // 如果数据包含sheets数组，取第一个sheet
  if (data.sheets && Array.isArray(data.sheets) && data.sheets.length > 0) {
      data = data.sheets[0]
  }

  // 确保数据有必要的属性
  if (!data.rows) data.rows = {}
  if (!data.cols) data.cols = { len: 26 }
  if (!data.merges) data.merges = []
  console.log("加载数据:", data)
  spreadsheetRef.value.loadData(data)
}

const exportexcel = (fileName:string) => {
  const data = spreadsheetRef.value.getData()
  const workbook = xtos(data);
  // @ts-ignore
  XLSX.writeFile(workbook, fileName);
}

const destroySpreadSheet = () => {
  visible.value = false
}

const visible = ref(false)
const jsonprettyvisible = ref(false)
const prtdata = () => {
  jsondata.value = spreadsheetRef.value.getData()
  jsonprettyvisible.value = true
}

const jsondata = ref({})

const copyJsonContent = () => {
  const content = JSON.stringify(jsondata.value, null, 2)
  navigator.clipboard.writeText(content).then(()=> {
    ElMessage({
      message: '复制成功.',
      type: 'success',
      showClose: true
    })
  })
}

const importdata = () => {
  importdatavisible.value = true
}
const importdatavisible = ref(false)

const importJsonStr = ref();
const importdataclick = () => {
  if(importJsonStr.value) {
    console.log("导入数据:", importJsonStr.value)
    spreadsheetRef.value.loadData(JSON.parse(importJsonStr.value))
    ElMessage({
      message: '导入成功.',
      type: 'success',
    })
    importdatavisible.value = false
  } else {
    ElMessage({
      message: '不能为空.',
      type: 'error',
      showClose: true
    })
  }
}

</script>

<template>
  <div>
    <div style="margin-top: 40px; margin-bottom: 20px;">
      <el-button type="primary" @click="initSpreadsheet">初始化</el-button>
      <el-button type="success" @click="loaddata">加载示例数据</el-button>
      <el-button type="success" @click="exportexcel('导出文件.xlsx')">导出excel</el-button>
      <el-button type="info" @click="prtdata">查看JSON</el-button>
      <el-button type="warning" @click="importdata">导入JSON</el-button>
      <el-button type="danger" @click="destroySpreadSheet">销毁</el-button>
    </div>
    <!-- container -->
    <div v-if="visible" ref="spreadsheetElRef" class="spreadsheet-container"></div>
    <el-dialog title="json查看" v-model="jsonprettyvisible">
      <div style="height: 50vh;overflow-y:scroll;border-top:1px solid lightgrey;">
            <vue-json-pretty :data="jsondata" style=""></vue-json-pretty>
          </div>
      <template #footer>
        <el-button type="primary" class="m-flow-btn-copy" @click="copyJsonContent">复制JSON</el-button>
      </template>
    </el-dialog>

    <el-dialog title="数据导入" v-model="importdatavisible">
      <div style="height:440px;overflow-y:scroll;">
        <el-input v-model="importJsonStr" :rows="20" type="textarea"></el-input>
      </div>
      <template #footer>
        <el-button type="primary" class="m-flow-btn-copy" @click="importdataclick">导入数据</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.spreadsheet-container {
    height: 80vh;
    width: 80vw;
    border: 1px solid #ddd;
    background-color: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    overflow: hidden;
}
</style>